package com.zerui.manager.openplan.scheduled;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.zerui.manager.openplan.OpenPlanImplementTask;
import com.zerui.manager.openplan.domainservice.OpenPlanTask;
import com.zerui.manager.openplan.gateway.OpenPlanGateWay;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author wh
 * @create_time 2023-06-28 14:56
 */
@Slf4j
@Component
public class OpenPlanImplementScheduled {

	@Resource
	private OpenPlanGateWay openPlanGateWay;
	@Resource
	private OpenPlanTask openPlanTask;

	/**
	 *
	 * 每天11点50分执行 添加第二天的任务
	 */
	@Scheduled(cron = "0 50 23 ? * *")
	public void initDelayQueueScheduled() {
		log.info("put openPlanImplement to DelayQueue scheduled task begin...,{}",LocalDateTime.now());
		try{
			String now = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
			List<OpenPlanImplementTask> task =  openPlanGateWay.selectImplementByTime(now);
			if(CollectionUtils.isNotEmpty(task)){
				task.forEach(e-> openPlanTask.addTsk(e.getId(),e.getOperationTime().toInstant(ZoneOffset.of("+8")).toEpochMilli()));
			}
			log.info("put digitalPlanImplement to MQ scheduled task end...");
		}catch (Exception e ) {
			log.info("put openPlanImplement to DelayQueue scheduled task failed... : {}" , e.getMessage());
		}
	}

	@EventListener(ContextRefreshedEvent.class)
	public void initDelayQueue(){
		log.info("执行计划初始化开始：{}", LocalDateTime.now());
		String now = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		List<OpenPlanImplementTask> task =  openPlanGateWay.selectImplementByTime(now);
		if(CollectionUtils.isNotEmpty(task)){
			task.forEach(e-> openPlanTask.addTsk(e.getId(),e.getOperationTime().toInstant(ZoneOffset.of("+8")).toEpochMilli()));
		}
		log.info("执行计划初始化结束：{}", LocalDateTime.now());
	}

}
